<?php
namespace app\model\common;

class SandPayImplementers
{
    /**
     * 生成签名
     * @Author Abnermouke <abnermouke@outlook.com>
     * @Originate in Abnermouke's MBP
     * @Time 2023-04-10 00:16:48
     * @param $data
     * @return string
     */
    public static function sign($data)
    {
        //移除非必要参数
        $data = Arr::except($data, ['expire_time', 'goods_name', 'product_code', 'clear_cycle', 'jump_scheme', 'meta_option', 'clear_cycle']);
        //升序排列
        ksort($data);
        //私钥加密
//        $priKey = self::formatRsaKey(file_get_contents(public_path('cert/sandpay/privite_key_PKS1.txt')));
        $priKey = "-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCnjm4z9cF2KHhfugo+pFj7lFJWmCJMeryWvgVn70dvaQm3YAbtpDM+Lr47v01vvPDM/EMhP2nuflZ3CKOX60zfpiTg/jhrbVZ6jY7+SrG1EkKToEtq1xx/Xd2KeKRyFCY5m0eGehNV2sVz9lukRD20LKJ44aLzxo1c++bEJhXheQIDAQABAoGAZsU4mMwipht6gZR1Viitn1lBC3Xyi6A4bekNHcuosA/n8r6GYVn2SCyZZ8IVd/SWadRMRGdFzQ9Wb1owJS0gj4ceomb2o1lVtk+XjVtrYBEK4ucKRkoOvUy0z57ZFlhaGLtXNHhHV3e2KHs/nGB7XuFkLhAKLpx1NOaux3+/0wECQQD0jXiBHWpC4vdhaKk47NiQV1LZiaFT6T2KRm3bVrsX0dtTDJrgogvABaMiy5c7DPYweYdq9xKEwHdZ3u6lQHahAkEAr2ZL2fxC28QvpvnhKrQyqoTw9xMeb6X5G0tFoXHulmCtptLqVDXXApuxDPtR+cyMaB1A/mELV+AO1RPGJsdz2QJBAOaq6hcfH7OnUZ9XkQZYoIzFUShPYRQ81AcxFz3kOOTm1PEo2o03S837gzy2vBa+yxg+CTUjhxwgTnM+i+rjOwECQBqpaBpImDkjx0KQdUOyhIkbEC3egB/kkMsvU/RIh0XgiET1hp0qWfaRiAY7JajdCPLCj6CbS8gdzONi0BoQ83ECQQCLiR2fr8UqyrymJf/xKHSz/iE2cpnyYBy3OKaWNYpJ7/Byb1CRv1L5JORepRyxqaaMQjkF3yBd+5Bw3qfzTAVQ
-----END RSA PRIVATE KEY-----";
        //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
        $res = openssl_get_privatekey($priKey);
        //调用openssl内置签名方法，生成签名$sign
        openssl_sign(self::urlParams($data), $sign, $res);
        //释放资源
        openssl_free_key($res);
        //返回加密结果
        return base64_encode($sign);
    }

    /**
     * 生成链接参数形式
     * @Author Abnermouke <abnermouke@outlook.com>
     * @Originate in Abnermouke's MBP
     * @Time 2023-04-10 00:21:37
     * @param $array
     * @return string
     */
    public static function urlParams($array)
    {
        //整理参数
        $params = [];
        //循环内容
        foreach ($array as $k => $val) {
            //设置信息
            $params[] = $k . '=' . str_replace(' ', '+', $val);
        }
        //组合参数
        return implode('&', $params);
    }

    /**
     * 生成密钥
     * @Author Abnermouke <abnermouke@outlook.com>
     * @Originate in Abnermouke's MBP
     * @Time 2023-04-10 00:16:32
     * @param $key
     * @param $alias
     * @return string
     */
    private static function formatRsaKey($key, $alias = 'RSA PRIVATE')
    {
        //生成pem
        $pem = "-----BEGIN $alias KEY-----\n".$key."-----END $alias KEY-----";
        //返回pem
        return $pem;
    }
}